package com.keter.common.domain.org;

import com.alibaba.fastjson.JSONObject;
import com.keter.common.base.BaseController;
import com.keter.framework.web.result.JSONResult;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

/**
 *  用户管理
 */
@RestController
@RequestMapping("/api/v1/orgs")
public class OrgController extends BaseController {

    @ApiOperation(value = "获取全部组织机构")
    @GetMapping
    public JSONResult findAll(){
        return wrap(Org.dao.findAll());
    }

    @ApiOperation(value = "根据ID获取组织机构")
    @GetMapping("/{id}")
    public JSONResult findById(
            @ApiParam(value = "逗号分隔的组织机构ID串", required = true)
            @PathVariable String id){
        return wrap(Org.dao.findById(id));
    }

    @ApiOperation(value = "根据ID获取多个组织机构")
    @GetMapping("/ids/{idStr}")
    public JSONResult findInIds(
            @ApiParam(value = "逗号分隔的多个组织机构ID", required = true)
            @PathVariable String idStr){
        return wrap(Org.dao.findInIds(idStr));
    }

    @ApiOperation(value = "获取组织机构下的用户")
    @GetMapping("/{id}/users")
    public JSONResult findUsersById(
            @ApiParam(value = "组织机构ID", required = true)
            @PathVariable String id){
        return wrap(Org.dao.findUsers(id));
    }

    @ApiOperation(value = "创建组织机构")
    @PostMapping
    public JSONResult add(
            @ApiParam(value = "组织机构对象", required = true)
            @RequestBody JSONObject obj) {
        Org org = new Org();
        org.set("name",obj.get("name"));
        org.set("type",obj.get("type"));
        org.set("status",obj.get("status"));
        org.set("email",obj.get("email"));
        org.set("contact",obj.get("contact"));
        org.set("contact_phone",obj.get("contact_phone"));
        org.set("contact_mobile",obj.get("contact_mobile"));
        org.set("address",obj.get("address"));
        org.set("remark",obj.get("remark"));
        org.save();
        return wrap(org);
    }

    @ApiOperation(value = "向组织机构添加用户")
    @PostMapping("/{orgId}/users")
    public JSONResult addUsers(
            @ApiParam(value = "组织机构ID", required = true)
            @PathVariable String orgId,
            @ApiParam(value = "逗号分隔的用户ID列表",example = "1,2,3",required = true)
            @RequestBody String userIds
    ){
        Arrays.stream(userIds.split(",")).forEach(
                userId -> Org.dao.addUser(orgId,userId)
        );
        return success();
    }

}
